package com.mbta.tracker;

import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

public class PredictionUpdater implements Runnable {
	private static final long MIN_REFRESH_TIME_MS = 10 * 1000;
	private final SQLiteDatabase m_db;
	private final Handler m_handler;
	private final Runnable m_callback;
	
	PredictionUpdater(Context context, Handler handler, Runnable onPredictionUpdate) {
		BusScheduleDBAdapter dbAdapter = new BusScheduleDBAdapter(context);
		m_db = dbAdapter.getWritableDatabase();
		m_handler = handler;
		m_callback = onPredictionUpdate;
	}

	@Override
	public void run() {
		
		while(true) {
			Cursor stopsToRequest = m_db.query("savedStops", new String[] {"stopId"}, null, null, null, null, null);
			List<Prediction> predictedTimes = RouteInfo.getPredictedTimes(stopsToRequest);
			ContentValues cv = new ContentValues(1);
			long updateTime = System.currentTimeMillis();
			long soonestUpdateEpochTime = Long.MAX_VALUE;
			for(Prediction pred : predictedTimes) {
				cv.put("stopId", pred.stopId);
				cv.put("minutesToNextStop", pred.minutesToArrival);
				cv.put("lastUpdateTime", updateTime);
				m_db.replace("predictions", null, cv);
				cv.clear();
				if(pred.nextUpdateEpochTime < soonestUpdateEpochTime) {
					soonestUpdateEpochTime = pred.nextUpdateEpochTime;
				}
			}
			
			m_handler.post(m_callback);
			
			try {
				Thread.sleep(Math.min(soonestUpdateEpochTime, updateTime + MIN_REFRESH_TIME_MS));
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
	}

}
